#include "WebServer.hh"


using namespace std;
using namespace System;

MyWebServer *server;


int
MyWebServer::evt_loop(void)
{
    // Loop forever
	return urlhook->evt_loop();
}


// Constructor
MyWebServer::MyWebServer ()
{
    status = STOP;

    ftdi_device = new FTDI_Device;
	if (true == ftdi_device->device_present()) {
		dbg_print("FTDI device present");
	} else {
		dbg_print("No FTDI device present");
	}
    urlhook = new UrlHook;
    // Attach callbacks
    urlhook->set_url_cb(QUERY_URL, new  query_url_called_cb(&querycb, this));
    urlhook->set_url_cb(START_URL, new  start_url_called_cb(&startcb, this));
    urlhook->set_url_cb(STOP_URL,  new  stop_url_called_cb(&stopcb, this));
}

MyWebServer::relay_state_e
MyWebServer::get_status(void)
{
    return status;
}

void
MyWebServer::relay_ON (void)
{
    int err;
    
    err = ftdi_device->pin_set(0, FTDI_Device::OUTPUT);
    if (0 != err) {
		printLog(0, "Error in Turning Relay ON");
		return;
    }
    err = ftdi_device->pin_write(0, true);
    if (0 != err) {
		printLog(0, "Error in motor function 1");
		return;
    }
}

void
MyWebServer::relay_OFF (void)
{
    int err;
    
    err = ftdi_device->pin_set(0, FTDI_Device::OUTPUT);
    if (0 != err) {
		printLog(0, "Error in Turning Relay ON");
		return;
    }
    err = ftdi_device->pin_write(0, false);
    if (0 != err) {
		printLog(0, "Error in motor function 1");
		return;
    }
}

// Define Url Hooks
int
QueryUrlHookCB::operator() (query_url_called_cb *mycb)
{
    char str[100];
    printLog(0, "Query Called");
    sprintf(str, "%s %s\n",
            "Device found = ",
            mycb->cookie()->ftdi_device->device_present() ? "True" : " False");
    mycb->cookie()->urlhook->reply_browser(str);
    return 0;
}

int
StartUrlHookCB::operator() (start_url_called_cb *mycb)
{
    printLog(0, "Start Called\n");
    mycb->cookie()->relay_ON();
    mycb->cookie()->urlhook->reply_browser("Relay ON\n");
    return 0;
}

int
StopUrlHookCB::operator() (stop_url_called_cb *mycb)
{
    printLog(0, "Stop Called\n");
    mycb->cookie()->relay_OFF();
    mycb->cookie()->urlhook->reply_browser("Relay OFF\n");
    return 0;
}
